package org.lifxue.jqda.ui;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;

import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lifxue.jqda.data.DataUtil;
import org.lifxue.jqda.data.bean.AppInfoBean;
import org.lifxue.jqda.util.GlobalVar;

/**
 * 
 * @Description:
 * @Author: zhangzuoqiang
 * @Date: Sep 26, 2011
 */
public class QuickStartSettingJDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Log logger = LogFactory
			.getLog(QuickStartSettingJDialog.class);
	private HashMap<String, List<String>> QS_DIR;// 扫描目录
	private HashMap<String, List<AppInfoBean>> QS_APP;// 扫描到的文件
	private static QuickStartSettingJDialog QS_JDIALOG;
	private int QS_LAYERNUMBERS;// 目录层深
	private IndexThread indexthread = null;

	public static QuickStartSettingJDialog getInstance(boolean modal) {
		synchronized (QuickStartSettingJDialog.class) {
			if (QS_JDIALOG == null) {
				QS_JDIALOG = new QuickStartSettingJDialog(modal);
			}
		}
		return QS_JDIALOG;
	}

	/**
	 * Creates new form QuickStartSettingJDialog
	 * 
	 * @param parent
	 * @param modal
	 */
	public QuickStartSettingJDialog(java.awt.Frame parent, boolean modal) {
		super(parent, modal);
		initComponents();
	}

	public QuickStartSettingJDialog(boolean modal) {
		super(new JFrame(), modal);
		init();

		initComponents();

		// 设置文件数量
		filesjLabel.setText("扫描到 " + String.valueOf(getAppCount()) + " 个文件");

		// 窗口定位
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = getSize();
		setLocation(new Point((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.width) / 2));

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">
	private void initComponents() {

		jScrollPane1 = new JScrollPane();
		DefaultListModel listModel = new DefaultListModel();
		// listModel.addElement("C:\\Program Files");
		Iterator<Entry<String, List<String>>> i = QS_DIR.entrySet().iterator();
		while (i.hasNext()) {
			Entry<String, List<String>> entry = (Entry<String, List<String>>) i
					.next();
			String key = (String) entry.getKey(); // 返回与此项对应的键
			listModel.addElement(key);
		}
		dirjList = new JList();
		addFileExtjButton = new JButton();
		deductFileExtjButton = new JButton();
		addDirjButton = new JButton();
		deductDirjButton = new JButton();
		jSeparator1 = new JSeparator();
		dirjCheckBox = new JCheckBox();
		jLabel1 = new JLabel();
		dirjSpinner = new JSpinner();
		scanjButton = new JButton();
		filesjLabel = new JLabel();
		dirjProgressBar = new JProgressBar();
		jSeparator2 = new JSeparator();
		canceljButton = new JButton();
		okjButton = new JButton();
		jScrollPane2 = new JScrollPane();
		fileExtjTable = new JTable();
		editjButton = new JButton();

		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		setTitle("快速启动设置");
		setIconImage(Toolkit.getDefaultToolkit().createImage(
				getClass().getResource("/org/lifxue/jqda/ui/butterfly16.png")));

		jScrollPane1.setBorder(BorderFactory.createTitledBorder("目录"));

		dirjList.setModel(listModel);
		dirjList.setValueIsAdjusting(false);
		dirjList.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent evt) {
				dirjListValueChanged(evt);
			}
		});
		jScrollPane1.setViewportView(dirjList);

		addFileExtjButton.setText("+");
		addFileExtjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				addFileExtjButtonActionPerformed(evt);
			}
		});

		deductFileExtjButton.setText("-");
		deductFileExtjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				deductFileExtjButtonActionPerformed(evt);
			}
		});

		addDirjButton.setText("+");
		addDirjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				addDirjButtonActionPerformed(evt);
			}
		});

		deductDirjButton.setText("-");
		deductDirjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				deductDirjButtonActionPerformed(evt);
			}
		});

		dirjCheckBox.setText("包含目录");
		dirjCheckBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent evt) {
				dirjCheckBoxItemStateChanged(evt);
			}
		});

		jLabel1.setText("深度:");

		dirjSpinner.setModel(new SpinnerNumberModel(0, 0, 100, 1));
		dirjSpinner.setValue(5);
		JSpinner.DefaultEditor s_edit = (JSpinner.DefaultEditor) dirjSpinner
				.getEditor();
		s_edit.getTextField().setEditable(false);
		dirjSpinner.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent evt) {
				dirjSpinnerStateChanged(evt);
			}
		});

		scanjButton.setText("扫描目录");
		scanjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				scanjButtonActionPerformed(evt);
			}
		});

		filesjLabel.setText("扫描到N个文件");

		dirjProgressBar.setStringPainted(true);

		canceljButton.setText("取消");
		canceljButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				canceljButtonActionPerformed(evt);
			}
		});

		okjButton.setText("确定");
		okjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				okjButtonActionPerformed(evt);
			}
		});

		jScrollPane2.setBorder(BorderFactory.createTitledBorder("文件类型"));
		jScrollPane2.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent evt) {
				jScrollPane2MouseClicked(evt);
			}
		});

		fileExtjTable.setRowHeight(fileExtjTable.getRowHeight() + 5);
		fileExtjTable.setBorder(BorderFactory.createEtchedBorder());
		fileExtjTable.setModel(new DefaultTableModel(new Object[][] {

		}, new String[] { "" }) {

			private static final long serialVersionUID = 1L;
			Class<?>[] types = new Class<?>[] { String.class };

			public Class<?> getColumnClass(int columnIndex) {
				return types[columnIndex];
			}
		});
		fileExtjTable.getTableHeader().setVisible(false);
		jScrollPane2.setViewportView(fileExtjTable);
		// fileExtjTable.setDefaultEditor(Object.class, new TableEditor());
		fileExtjTable.getColumnModel().getColumn(0)
				.setCellEditor(new TableEditor());

		editjButton.setText("手动编辑");
		editjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				editjButtonActionPerformed(evt);
			}
		});

		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jScrollPane1,
										GroupLayout.DEFAULT_SIZE, 438,
										Short.MAX_VALUE)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addGap(18, 18,
																		18)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.LEADING)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										addFileExtjButton,
																										GroupLayout.PREFERRED_SIZE,
																										39,
																										GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(
																										LayoutStyle.ComponentPlacement.RELATED,
																										17,
																										Short.MAX_VALUE)
																								.addComponent(
																										deductFileExtjButton,
																										GroupLayout.PREFERRED_SIZE,
																										47,
																										GroupLayout.PREFERRED_SIZE))
																				.addComponent(
																						dirjCheckBox)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jLabel1)
																								.addPreferredGap(
																										LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										dirjSpinner,
																										GroupLayout.PREFERRED_SIZE,
																										63,
																										GroupLayout.PREFERRED_SIZE)))
																.addGap(19, 19,
																		19))
												.addGroup(
														layout.createSequentialGroup()
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED)
																.addComponent(
																		jScrollPane2,
																		GroupLayout.DEFAULT_SIZE,
																		136,
																		Short.MAX_VALUE)
																.addContainerGap())))
				.addGroup(
						layout.createSequentialGroup()
								.addGap(90, 90, 90)
								.addComponent(addDirjButton,
										GroupLayout.PREFERRED_SIZE, 84,
										GroupLayout.PREFERRED_SIZE)
								.addGap(81, 81, 81)
								.addComponent(deductDirjButton,
										GroupLayout.PREFERRED_SIZE, 95,
										GroupLayout.PREFERRED_SIZE)
								.addContainerGap(231, Short.MAX_VALUE))
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jSeparator1,
										GroupLayout.DEFAULT_SIZE, 580,
										Short.MAX_VALUE).addContainerGap())
				.addGroup(
						GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addGap(176, 176, 176)
								.addComponent(filesjLabel,
										GroupLayout.PREFERRED_SIZE, 186,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED,
										148, Short.MAX_VALUE)
								.addComponent(scanjButton).addContainerGap())
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(dirjProgressBar,
										GroupLayout.DEFAULT_SIZE, 580,
										Short.MAX_VALUE).addContainerGap())
				.addComponent(jSeparator2, GroupLayout.DEFAULT_SIZE, 592,
						Short.MAX_VALUE)
				.addGroup(
						GroupLayout.Alignment.TRAILING,
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(editjButton)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED,
										382, Short.MAX_VALUE)
								.addComponent(okjButton).addGap(18, 18, 18)
								.addComponent(canceljButton).addContainerGap()));

		layout.linkSize(SwingConstants.HORIZONTAL, new java.awt.Component[] {
				addDirjButton, deductDirjButton });

		layout.linkSize(SwingConstants.HORIZONTAL, new java.awt.Component[] {
				addFileExtjButton, deductFileExtjButton });

		layout.setVerticalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		jScrollPane1,
																		GroupLayout.PREFERRED_SIZE,
																		217,
																		GroupLayout.PREFERRED_SIZE)
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.LEADING,
																				false)
																				.addComponent(
																						addDirjButton,
																						GroupLayout.DEFAULT_SIZE,
																						GroupLayout.DEFAULT_SIZE,
																						Short.MAX_VALUE)
																				.addComponent(
																						deductDirjButton,
																						GroupLayout.DEFAULT_SIZE,
																						GroupLayout.DEFAULT_SIZE,
																						Short.MAX_VALUE)))
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		jScrollPane2,
																		GroupLayout.PREFERRED_SIZE,
																		142,
																		GroupLayout.PREFERRED_SIZE)
																.addGap(10, 10,
																		10)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.BASELINE)
																				.addComponent(
																						addFileExtjButton)
																				.addComponent(
																						deductFileExtjButton))
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.UNRELATED)
																.addComponent(
																		dirjCheckBox)
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.CENTER)
																				.addComponent(
																						jLabel1)
																				.addComponent(
																						dirjSpinner,
																						GroupLayout.PREFERRED_SIZE,
																						GroupLayout.DEFAULT_SIZE,
																						GroupLayout.PREFERRED_SIZE))))
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jSeparator1,
										GroupLayout.PREFERRED_SIZE, 10,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.BASELINE)
												.addComponent(scanjButton)
												.addComponent(filesjLabel))
								.addGap(10, 10, 10)
								.addComponent(dirjProgressBar,
										GroupLayout.PREFERRED_SIZE,
										GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(jSeparator2,
										GroupLayout.PREFERRED_SIZE, 10,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.BASELINE)
												.addComponent(canceljButton)
												.addComponent(okjButton)
												.addComponent(editjButton))
								.addContainerGap(GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void canceljButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_canceljButtonActionPerformed
		// TODO add your handling code here:
		this.setVisible(false);
		this.dispose();
		QS_JDIALOG = null;

	}// GEN-LAST:event_canceljButtonActionPerformed

	private void okjButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_okjButtonActionPerformed
		// TODO add your handling code here:
		closeEditing();
		GlobalVar.APP_SCAN_DIR = this.QS_DIR;
		GlobalVar.APPLICATIONS = this.QS_APP;
		DataUtil.updateAppsFile();
		// 关闭QuickStartJFrame实例
		// QuickStartJFrame qs = QuickStartJFrame.getInstance();
		// qs.updateData();

		canceljButtonActionPerformed(evt);

		QuickStartListDialog QSList = QuickStartListDialog.getInstance(true);
		QSList.initTableData();
	}// GEN-LAST:event_okjButtonActionPerformed

	private void addDirjButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_addDirjButtonActionPerformed
		// TODO add your handling code here:
		closeEditing();
		// 建立文件选择框对象
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		// 设定文件选择框标题
		fc.setDialogTitle("选择目录");
		// 显示文件选择框，在选择后将结果储存到returnVal变量中
		int returnVal = fc.showSaveDialog(this);
		// 如果用户选择了文件，并点击了"Opne/打开"按钮，显示用户选择的文件全名路径，
		// 如果用户点击"Close/关闭"按钮，以及其它方式退出文件选择框，则什么也不做。
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			if (file == null) {
				return;
			}
			DefaultListModel listModel = (DefaultListModel) dirjList.getModel();
			for (int i = 0; i < listModel.getSize(); i++) {
				String temp = (String) listModel.get(i);
				if (temp.equals(file.getPath())) {// 如果重复目录，跳过，不保存
					dirjList.setSelectedIndex(i);
					return;
				}
			}
			listModel.addElement(file.getPath());
			QS_DIR.put(file.getPath(), new ArrayList<String>());
			dirjList.setSelectedIndex(listModel.getSize() - 1);
		}
	}// GEN-LAST:event_addDirjButtonActionPerformed

	private void deductDirjButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_deductDirjButtonActionPerformed
		// TODO add your handling code here:
		closeEditing();
		DefaultListModel model = (DefaultListModel) dirjList.getModel();
		int[] indexs = dirjList.getSelectedIndices();
		Object[] obj = dirjList.getSelectedValues();
		for (int i = indexs.length - 1; i >= 0; i--) {
			// logger.debug(indexs[i]);
			model.remove(indexs[i]);
			QS_DIR.remove(obj[i].toString());
		}
		// 清空table
		DefaultTableModel tablemodel = (DefaultTableModel) fileExtjTable
				.getModel();
		int allcount = tablemodel.getRowCount();
		for (int i = allcount - 1; i >= 0; i--) {
			tablemodel.removeRow(i);
		}
		tablemodel.setRowCount(0);
	}// GEN-LAST:event_deductDirjButtonActionPerformed

	private void dirjListValueChanged(ListSelectionEvent evt) {// GEN-FIRST:event_dirjListValueChanged
		// TODO add your handling code here:
		closeEditing();
		boolean adjust = evt.getValueIsAdjusting();
		if (!adjust) {
			JList list = (JList) evt.getSource();
			if (!list.isSelectionEmpty()) {
				String text = list.getSelectedValue().toString();

				DefaultTableModel model = (DefaultTableModel) fileExtjTable
						.getModel();
				int allcount = model.getRowCount();
				for (int i = allcount - 1; i >= 0; i--) {
					model.removeRow(i);
				}
				model.setRowCount(0);

				Iterator<Entry<String, List<String>>> i = QS_DIR.entrySet()
						.iterator();
				while (i.hasNext()) {
					Entry<String, List<String>> entry = (Entry<String, List<String>>) i
							.next();
					String key = (String) entry.getKey(); // 返回与此项对应的键
					List<String> value = (List<String>) entry.getValue(); // 返回与此项对应的值
					if (key.equals(text)) {
						for (String str : value) {
							Object[] obj = new Object[1];
							obj[0] = str;
							model.addRow(obj);
						}
					}
				}
			}
		}
	}

	private void addFileExtjButtonActionPerformed(ActionEvent evt) {
		if (dirjList.getSelectedIndex() > -1) {
			closeEditing();

			DefaultTableModel model = (DefaultTableModel) fileExtjTable
					.getModel();
			Object[] obj = new Object[1];
			model.addRow(obj);
			int allcount = model.getRowCount();
			fileExtjTable.editCellAt(allcount - 1, 0);
			((DefaultCellEditor) fileExtjTable.getCellEditor()).getComponent()
					.requestFocusInWindow();

			// fileExtjTable.getCellEditor().addCellEditorListener(new
			// CellEditorAction());
		}
	}

	private void deductFileExtjButtonActionPerformed(ActionEvent evt) {
		closeEditing();

		DefaultTableModel model = (DefaultTableModel) fileExtjTable.getModel();
		int allcount = model.getRowCount();
		int[] count = fileExtjTable.getSelectedRows();// 选中的行号
		for (int i = count.length - 1; i >= 0; i--) {
			model.removeRow(count[i]);
		}
		model.setRowCount(allcount - count.length);
		// 更新数据
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < model.getRowCount(); i++) {
			// logger.debug(model.getValueAt(i, 0));
			list.add(model.getValueAt(i, 0).toString());
		}
		QS_DIR.put(dirjList.getSelectedValue().toString(), list);
	}

	private void jScrollPane2MouseClicked(MouseEvent evt) {
		closeEditing();
	}

	private void scanjButtonActionPerformed(ActionEvent evt) {
		closeEditing();
		dirjProgressBar.setValue(0);
		filesjLabel.setText("扫描到 " + 0 + " 个文件");
		QS_APP = GlobalVar.APPLICATIONS;
		if (QS_DIR.isEmpty()) {// 没有数据
			dirjProgressBar.setValue(100);
			return;
		}

		if (indexthread == null) {
			indexthread = new IndexThread();
			indexthread.start();
		}
	}

	class IndexThread extends Thread {

		@Override
		public void run() {
			int size = QS_DIR.size();
			int piece = 100 / size;
			if (100 % size > 0) {
				piece += 1;
			}
			final int a = piece;
			Iterator<Entry<String, List<String>>> i = QS_DIR.entrySet()
					.iterator();
			while (i.hasNext()) {
				Entry<String, List<String>> entry = (Entry<String, List<String>>) i
						.next();
				String key = (String) entry.getKey(); // 返回与此项对应的键
				indexDocs(0, new File(key));
				SwingUtilities.invokeLater(new Runnable() {

					@Override
					public void run() {
						int value = dirjProgressBar.getValue();
						if (value < 100) {
							value += a;
							dirjProgressBar.setValue(value > 100 ? 100 : value);
						}
						// 设置文件数量
						filesjLabel.setText("扫描到 "
								+ String.valueOf(getAppCount()) + " 个文件");
					}
				});
			}
		}
	}

	/**
	 * 复选框事件
	 * 
	 * @param evt
	 */
	private void dirjCheckBoxItemStateChanged(ItemEvent evt) {
		closeEditing();
		if (evt.getStateChange() == ItemEvent.SELECTED) {// 被选中状态
			if (evt.getSource() == dirjCheckBox) {
				QS_LAYERNUMBERS = Integer.parseInt(dirjSpinner.getValue()
						.toString());
			}
		} else {// 取消选中状态
			if (evt.getSource() == dirjCheckBox) {
				QS_LAYERNUMBERS = 0;
			}
		}
	}

	private void dirjSpinnerStateChanged(ChangeEvent evt) {
		closeEditing();
		if (evt.getSource() == dirjSpinner) {
			QS_LAYERNUMBERS = Integer.parseInt(dirjSpinner.getValue()
					.toString());
		}
	}

	private void editjButtonActionPerformed(ActionEvent evt) {
		// 手动编辑快速启动列表
		// 打开列表窗口，增删改操作
		QuickStartListDialog QSList = QuickStartListDialog.getInstance(true);
		QSList.setVisible(true);
	}

	/**
	 * 
	 * @param index
	 *            目录深度
	 * @param file
	 */
	private void indexDocs(int index, File file) {
		// do not try to index files that cannot be read
		if (file.canRead()) {
			if (file.isDirectory()) {
				String[] files = file.list();
				// an IO error could occur
				if (files != null) {
					// logger.debug(dirjSpinner.getValue());
					if (index > QS_LAYERNUMBERS) {
						// logger.debug("深度是"+dirjSpinner.getValue());
						return;
					}
					index++;
					for (int i = 0; i < files.length; i++) {
						indexDocs(index, new File(file, files[i]));
					}
				}
			} else {
				String fileName = file.getName().toLowerCase(Locale.CHINESE);
				String fileType = fileName
						.substring(fileName.lastIndexOf(".") + 1);

				// logger.debug(file.getPath());
				String[] split = file.getPath().split("\\\\");
				StringBuilder tempdir = new StringBuilder();
				for (int i = 0; i < split.length - 1 - index; i++) {
					// logger.debug(split[i]);
					tempdir.append(split[i]);
					tempdir.append("\\");
				}
				tempdir.append(split[split.length - 1 - index]);
				// logger.debug(tempdir.toString());

				List<String> list = (List<String>) QS_DIR.get(tempdir
						.toString());
				if (list == null || list.isEmpty()) {
					return;
				}
				for (String ext : list) {
					String tempfileType = ext
							.substring(ext.lastIndexOf(".") + 1);
					if (tempfileType.equals(fileType)) {
						List<AppInfoBean> pathlist = (List<AppInfoBean>) QS_APP
								.get(fileName);
						if (pathlist == null || pathlist.isEmpty()) {
							pathlist = new ArrayList<AppInfoBean>();
							AppInfoBean appinfo = new AppInfoBean();
							appinfo.setPath(file.getPath());
							pathlist.add(appinfo);
							QS_APP.put(fileName, pathlist);
							break;
						}

						boolean isFound = false;
						for (int i = 0; i < pathlist.size(); i++) {
							AppInfoBean appinfo = new AppInfoBean();
							appinfo = pathlist.get(i);
							if (appinfo.getPath().equals(file.getPath())) {
								isFound = true;
								break;
							}
						}
						if (!isFound) {
							AppInfoBean appinfo = new AppInfoBean();
							appinfo.setPath(file.getPath());
							pathlist.add(appinfo);
						}
						QS_APP.put(fileName, pathlist);
						break;
					}
				}

			}
		}
	}

	/**
	 * 关闭table的编辑状态
	 */
	private void closeEditing() {
		if (fileExtjTable.isEditing()) {
			fileExtjTable.getCellEditor().stopCellEditing();
		}
	}

	/**
	 * 初始化
	 */
	private void init() {
		QS_DIR = GlobalVar.APP_SCAN_DIR;
		QS_APP = GlobalVar.APPLICATIONS;

		QS_LAYERNUMBERS = 0;// 初始化目录层深为0

	}

	/**
	 * 计算扫描到的文件个数
	 * 
	 * @return
	 */
	private int getAppCount() {
		int appCount = 0;
		Iterator<Entry<String, List<AppInfoBean>>> app = QS_APP.entrySet()
				.iterator();
		while (app.hasNext()) {
			Entry<String, List<AppInfoBean>> entry = (Entry<String, List<AppInfoBean>>) app
					.next();
			// String key = (String) entry.getKey(); // 返回与此项对应的键
			List<AppInfoBean> list = (List<AppInfoBean>) entry.getValue();
			appCount += list.size();
		}
		return appCount;
	}

	private class TableEditor extends DefaultCellEditor {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public TableEditor() {
			super(new JTextField());
		}

		@Override
		public boolean stopCellEditing() {
			String value = (String) getCellEditorValue();
			try {
				Object dir = dirjList.getSelectedValue();
				Iterator<Entry<String, List<String>>> i = QS_DIR.entrySet()
						.iterator();
				while (i.hasNext()) {
					Entry<String, List<String>> entry = (Entry<String, List<String>>) i
							.next();
					String key = (String) entry.getKey(); // 返回与此项对应的键
					List<String> list = (List<String>) entry.getValue(); // 返回与此项对应的值
					if (key.equals(dir.toString())) {
						list.clear();
						DefaultTableModel model = (DefaultTableModel) fileExtjTable
								.getModel();
						for (int count = 0; count < fileExtjTable.getRowCount(); count++) {
							if (count == fileExtjTable.getEditingRow()) {
								list.add(value);
							} else {
								list.add(model.getValueAt(count, 0).toString());
							}
						}
						QS_DIR.put(key, list);
					}
				}

			} catch (NumberFormatException e) {
				logger.debug(e);
			}
			return super.stopCellEditing();
		}
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				QuickStartSettingJDialog dialog = new QuickStartSettingJDialog(
						new JFrame(), true);
				dialog.addWindowListener(new WindowAdapter() {

					@Override
					public void windowClosing(WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

	private JButton addDirjButton;
	private JButton addFileExtjButton;
	private JButton canceljButton;
	private JButton deductDirjButton;
	private JButton deductFileExtjButton;
	private JCheckBox dirjCheckBox;
	private JList dirjList;
	private JProgressBar dirjProgressBar;
	private JSpinner dirjSpinner;
	private JButton editjButton;
	private JTable fileExtjTable;
	private JLabel filesjLabel;
	private JLabel jLabel1;
	private JScrollPane jScrollPane1;
	private JScrollPane jScrollPane2;
	private JSeparator jSeparator1;
	private JSeparator jSeparator2;
	private JButton okjButton;
	private JButton scanjButton;
}
